<?php
namespace Api\Controller;
use Api\Controller\CommonController;
class ShopController extends CommonController {
    //店铺列表
	public function shopList(){
		//file_put_contents("geterror.txt", json_encode($_POST)." 日期：".date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
		
		$filed="shopID,shopName,province,city,district,address,headImg,thumb";
		$filed.=",shopGrade,goodsGrade,orderNum,saleNum,goodsCommentNum";
		$filed.=",shopCommentNum,shopType,allowCard,x as lng,y as lat";
		$filed.=",oilPriceJson";
		/***** 筛选 *****/
		//商店类型筛选
		
    	!empty($_POST['shopType'])&&in_array($_POST['shopType'],array(1,2,3))?$where['shopType']=intval(I("post.shopType")):$where['shopType']=0;
        
    	//允许使用汇通卡筛选
    	isset($_POST['allowCard'])&&in_array($_POST['allowCard'],array(0,1))?$where['allowCard']=intval(I("post.allowCard")):"";
    	
    	//省份筛选
    	!empty($_POST['province'])?$where['province']=I("post.province"):"";
    	
    	//市筛选
    	!empty($_POST['city'])?$where['city']=I("post.city"):"";
    	
    	//区筛选
    	!empty($_POST['district'])?$where['district']=I("post.district"):"";
    	
    	//是否显示附近
    	if(isset($_POST['isShowDistance'])&& ($_POST['isShowDistance']==1 ||$_POST['isShowDistance']==2)){
    		//清除地域选择
    		unset($where['province']);
    		unset($where['city']);
    		unset($where['district']);
    		
    		//附近
    		if ($_POST['isShowDistance']==1) {
    			if(empty($_POST['location'])) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    			
    			$location=explode(",", I("post.location"));
    			$lng=$location[0];
    			$lat=$location[1];
    			
    			$where['x']=array('exp',' is not null ');
    			$where['y']=array('exp',' is not null ');
    			$filed.=",(POWER(MOD(ABS(x - ".$lng."),360),2) + POWER(ABS(y - ".$lat."),2)) AS distance";
    		}
    		//地图范围
    		elseif ($_POST['isShowDistance']==2) {
    			if(empty($_POST['range'])) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    			$rangeArray=json_decode($_POST['rang'],true);
    			if(is_null($rangeArray)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    			
    			foreach ($rangeArray as $a){
    				if (!empty($a['lng1']) && !empty($a['lat1']) && !empty($a['lng2']) && !empty($a['lat2'])) {
    					$rangeLng[]=array(array('egt',$a['lng1']),array('lt',$a['lng2']),'and');
    					$rangeLat[]=array(array('egt',$a['lat1']),array('lt',$a['lat2']),'and');
    				}
    			}
    			
    			$rangeLng[]="OR";
    			$rangeLat[]="OR";
    			$where['x']=array($rangeLng);
    			$where['y']=array($rangeLat);
    		}
    	}
    	
    	/**** 排序 ****/
    	switch (I("post.order")){
    		case "shopGrade" :		//商店评分
    		case "goodsGrade" :		//商品评分
    		case "orderNum" :		//订单数量
    		case "saleNum" :		//交易数
    		case "goodsCommentNum" :		//商品评分数量
    		case "shopCommentNum" :		//商店评分数量
    		case "allowCard" :		//是否可使用汇通卡
    			$order=I("post.order");
    			break;
    		case "near" :
    			$order="distance";	//距离
    			break;
    		case "time" :			//店铺创建时间
    			$order="addTime";
    			break;
    		default:
    			$order="addTime";
    			break;
    	}
    	
    	/**** 降序升序 ****/
    	switch (I("post.isDesc")){
    		case 0 :
    			$sort="asc";
    			break;
    		default:
    			$sort="desc";
    			break;
    	}
    	
    	$where['isOn']=1;	//正常的商店
    	$where['isWork']=1;   //营业中的店
		
    	empty($_POST['page'])?$page=1:$page=intval(I("post.page"));
    	empty($_POST['pageSize'])?$pageSize=15:$pageSize=intval(I("post.pageSize"));
    	//empty($_POST['isShowDistance'])?$isShowDistance=1:$isShowDistance=0;
    	
    	$count=D("Shop")->getShopListLength($where);
    	if($count==0) $this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"139"));
    	
    	if ($_POST['isShowDistance']==1) {
	    	$pp=intval($count)/$pageSize;
	    	if ($count % $pageSize!=0)  $pageCount=intval($pp)+1;
	    	else $pageCount=$pp;
	    	
	    	if ($pageCount < $page) $this->_returnJson(array("result"=>0,"info"=>"page too big","code"=>"114"));
	    }
    	else{
    		$page=1;
    		$pageSize=100000;   //最多输出10W条数据
    		$pageCount=1;
    	}
    	
       $list=D("Shop")->getShopList($page, $pageSize, $where, $order." ".$sort,$filed);
       if(count($list)==0) $this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"139"));
       
       //处理数据
	   foreach ($list as $key=>$a){
	       if ($where['shopType']==1) {       //当商店为油站的时候，输出油信息
	       		$oilTemp=json_decode($a['oilPriceJson'],true);
				$list[$key]['headImg'] = C('IMG_DOMAIN').'/'.$a['headImg'];
	       		
	       		/* //兼容旧版本，输出三个
	       		$oilNum=count($oilTemp);
	       		$oilNumM=$oilNum-3;
	       		if($oilNum==0){
	       			$oilTemp=array(
	       					['name'=>'参考价0#','price'=>'6.21'],
	       					['name'=>'参考价93#','price'=>'6.6'],
	       					['name'=>'参考价97#','price'=>'7.15']					);
	       		}
	       		elseif ($oilNumM<0){
	       			for ($i=0;$i<(abs($oilNumM));$i++){
	       				$oilTemp[]=array(
	       					'name'=>'暂无油价',
	       					'price'=>'0.00'
	       				);
	       			}
	       		}
	       		elseif($oilNumM>0){
	       			$oilTemp=[$oilTemp[0],$oilTemp[1],$oilTemp[2]];
	       		} */
	       		
	       		$list[$key]['oilPrice']=$oilTemp;
	       }
	       elseif($where['shopType']==2){
	           
	       }
	       
	       unset($list[$key]['oilPriceJson']);
	   }                            
       
	   if ($where['shopType']==1||$where['shopType']==2) {
	       $this->_dealShopList($list,1);
	   }
	   
	   //显示附近的时候计算距离
	   if ($_POST['isShowDistance']==1) {
			$location=explode(",", I("post.location"));
			$lng=$location[0];
			$lat=$location[1];
				
			foreach ($list as $key=>$a){
				$dis=number_format($this->_getDistance($lat,$lng, $a['lat'], $a['lng']), 2, '.', '').' Km';  //Km
				$list[$key]['distance']=$dis;
				$list[$key]['shopName']=mb_substr($a['shopName'], 0,12*3,"utf-8");
				$list[$key]['address']=mb_substr($a['address'], 0,14*3,"utf-8");
			}
		}
		
		//dump($list);
		//echo D("Shop")->getLastSql();
		
		//file_put_contents("getShopSql.txt", D("Shop")->getLastSql());
		//file_put_contents("getJson.txt", json_encode(array("result"=>1,"list"=>$list,"page"=>array("page"=>$page,"pageSize"=>$pageSize,"pageCount"=>0))));
		$this->_returnJson(array("result"=>1,"list"=>$list,"page"=>array("page"=>$page,"pageSize"=>$pageSize,"pageCount"=>$pageCount,"count"=>$count)));
	}
	
	public function randomShopList(){
		//file_put_contents("geterror.txt", json_encode($_POST)." 日期：".date("Y-m-d H:i:s",time()).PHP_EOL,FILE_APPEND);
		
		$filed="shopID,shopName,province,city,district,address,headImg,thumb";
		$filed.=",shopGrade,goodsGrade,orderNum,saleNum,goodsCommentNum";
		$filed.=",shopCommentNum,shopType,allowCard,x as lng,y as lat";
		$filed.=",oilPriceJson";
		/***** 筛选 *****/
		//商店类型筛选
    	//!empty($_POST['shopType'])&&in_array($_POST['shopType'],array(1,2,3))?$where['shopType']=intval(I("post.shopType")):$where['shopType']=0;
		!empty($_POST['shopType'])&&in_array($_POST['shopType'],array(1,2,3))?$where['shopType']=intval(I("post.shopType")):"";
        
    	//允许使用汇通卡筛选
    	isset($_POST['allowCard'])&&in_array($_POST['allowCard'],array(0,1))?$where['allowCard']=intval(I("post.allowCard")):"";
    	
    	//省份筛选
    	!empty($_POST['province'])?$where['province']=I("post.province"):"";
    	
    	//市筛选
    	!empty($_POST['city'])?$where['city']=I("post.city"):"";
    	
    	//区筛选
    	!empty($_POST['district'])?$where['district']=I("post.district"):"";
    	
    	//是否显示附近
    	if(isset($_POST['isShowDistance'])&& ($_POST['isShowDistance']==1 ||$_POST['isShowDistance']==2)){
    		//清除地域选择
    		unset($where['province']);
    		unset($where['city']);
    		unset($where['district']);
    		
    		//附近
    		if ($_POST['isShowDistance']==1) {
    			if(empty($_POST['location'])) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    			
    			$location=explode(",", I("post.location"));
    			$lng=$location[0];
    			$lat=$location[1];
    			
    			$where['x']=array('exp',' is not null ');
    			$where['y']=array('exp',' is not null ');
    			$filed.=",(POWER(MOD(ABS(x - ".$lng."),360),2) + POWER(ABS(y - ".$lat."),2)) AS distance";
    		}
    		//地图范围
    		elseif ($_POST['isShowDistance']==2) {
    			if(empty($_POST['range'])) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    			$rangeArray=json_decode($_POST['rang'],true);
    			if(is_null($rangeArray)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    			
    			foreach ($rangeArray as $a){
    				if (!empty($a['lng1']) && !empty($a['lat1']) && !empty($a['lng2']) && !empty($a['lat2'])) {
    					$rangeLng[]=array(array('egt',$a['lng1']),array('lt',$a['lng2']),'and');
    					$rangeLat[]=array(array('egt',$a['lat1']),array('lt',$a['lat2']),'and');
    				}
    			}
    			
    			$rangeLng[]="OR";
    			$rangeLat[]="OR";
    			$where['x']=array($rangeLng);
    			$where['y']=array($rangeLat);
    		}
    	}
    	
    	
    	
    	$where['isOn']=1;	//正常的商店
    	$where['isWork']=1;   //营业中的店
		
    	//empty($_POST['page'])?$page=1:$page=intval(I("post.page"));
    	//empty($_POST['pageSize'])?$pageSize=4:$pageSize=intval(I("post.pageSize"));
    	//empty($_POST['isShowDistance'])?$isShowDistance=1:$isShowDistance=0;
		
		empty($_POST['limit'])?$limit=4:$limit=intval(I("post.limit"));
    	
    	/*$count=D("Shop")->getShopListLength($where);
    	if($count==0) $this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"139"));
    	
    	if ($_POST['isShowDistance']==1) {
	    	$pp=intval($count)/$pageSize;
	    	if ($count % $pageSize!=0)  $pageCount=intval($pp)+1;
	    	else $pageCount=$pp;
	    	
	    	if ($pageCount < $page) $this->_returnJson(array("result"=>0,"info"=>"page too big","code"=>"114"));
	    }
    	else{
    		$page=1;
    		$pageSize=100000;   //最多输出10W条数据
    		$pageCount=1;
    	}*/
    	
       $list=D("Shop")->getRandomShopList($limit, $where, $filed);
       if(count($list)==0) $this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"139"));
       
       //处理数据
	   foreach ($list as $key=>$a){
	       if ($where['shopType']==1) {       //当商店为油站的时候，输出油信息
	       		$oilTemp=json_decode($a['oilPriceJson'],true);
	       		
	       		/* //兼容旧版本，输出三个
	       		$oilNum=count($oilTemp);
	       		$oilNumM=$oilNum-3;
	       		if($oilNum==0){
	       			$oilTemp=array(
	       					['name'=>'参考价0#','price'=>'6.21'],
	       					['name'=>'参考价93#','price'=>'6.6'],
	       					['name'=>'参考价97#','price'=>'7.15']					);
	       		}
	       		elseif ($oilNumM<0){
	       			for ($i=0;$i<(abs($oilNumM));$i++){
	       				$oilTemp[]=array(
	       					'name'=>'暂无油价',
	       					'price'=>'0.00'
	       				);
	       			}
	       		}
	       		elseif($oilNumM>0){
	       			$oilTemp=[$oilTemp[0],$oilTemp[1],$oilTemp[2]];
	       		} */
	       		
	       		$list[$key]['oilPrice']=$oilTemp;
	       }
	       elseif($where['shopType']==2){
	           
	       }
	       
	       unset($list[$key]['oilPriceJson']);
			$list[$key]['headImg']=C('IMG_DOMAIN').'/'.$a['headImg'];
	   }                            
       
	   if ($where['shopType']==1||$where['shopType']==2) {
	       $this->_dealShopList($list,1);
	   }
	   
	   //显示附近的时候计算距离
	   if ($_POST['isShowDistance']==1) {
			$location=explode(",", I("post.location"));
			$lng=$location[0];
			$lat=$location[1];
				
			foreach ($list as $key=>$a){
				$dis=number_format($this->_getDistance($lat,$lng, $a['lat'], $a['lng']), 2, '.', '').' Km';  //Km
				$list[$key]['distance']=$dis;
				$list[$key]['shopName']=mb_substr($a['shopName'], 0,12*3,"utf-8");
				$list[$key]['address']=mb_substr($a['address'], 0,14*3,"utf-8");
				
			}
		}
		
		//dump($list);exit;
		//echo D("Shop")->getLastSql();
		
		//file_put_contents("getShopSql.txt", D("Shop")->getLastSql());
		//file_put_contents("getJson.txt", json_encode(array("result"=>1,"list"=>$list,"page"=>array("page"=>$page,"pageSize"=>$pageSize,"pageCount"=>0))));
		$this->_returnJson(array("result"=>1,"list"=>$list));
	}
    
    //单个店铺
    public function shop(){
    	!empty($_POST['shopID'])?$shopID=intval(I("post.shopID")):$this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    	
    	$where['isOn']=1;
    	$shop=D("Shop")->getShop("",$shopID,$where);
    	
    	if (!$shop) $this->_returnJson(array("result"=>0,"info"=>"shop not exist","code"=>"115"));
    	if ($shop['isWork']!=1) $this->_returnJson(array("result"=>0,"info"=>"shop has close","code"=>"122"));
		
		if($shop['shopType']==1){
			$oilTemp=json_decode($shop['oilPriceJson'],true);
		} else{
			$oilTemp=null;
		}
    	$return=array(
    			"shopID"=>$shop['shopID'],
    			"shopName"=>$shop['shopName'],
    			"province"=>$shop['province'],
    			"city"=>$shop['city'],
    			"district"=>$shop['district'],
    			"address"=>$shop['address'],
    			"desc"=>$shop['desc'],
    			"x"=>floatval($shop['x']),
    			"y"=>floatval($shop['y']),
    			"headImg"=>C('IMG_DOMAIN').'/'.$shop['headImg'],
    			"thumb"=>$shop['thumb'],
    			"shopGrade"=>$shop['shopGrade'],
    			"goodsGrade"=>$shop['goodsGrade'],
    			"orderNum"=>$shop['orderNum'],
    			"saleNum"=>$shop['saleNum'],
    			"goodsCommentNum"=>$shop['goodsCommentNum'],
    			"shopCommentNum"=>$shop['shopCommentNum'],
    			"shopType"=>$shop['shopType'],
    			"allowCard"=>$shop['allowCard'],
    			"isWork"=>$shop['isWork'],
				"oilPrice"=>$oilTemp
    	);
    	
    	//卷码判断
    	$count=D("Goods")->where(array("commentType"=>1,"isOn"=>1,"isSale"=>1,"shopID"=>$shop['shopID']))->count();
    	
	    if ($count>0) $return['isTicket']="1";
	    else $return['isTicket']="0";
	    
	    //file_put_contents("aa.txt", D("Shop")->getLastSql());
    	$this->_returnJson(array("result"=>1,"shop"=>$return));
    }
    
    //获取商品
    public function goodsList(){
    	!empty($_POST['shopID'])?$where['shopID']=intval(I("post.shopID")):"";
    	!empty($_POST['catID'])?$where['catID']=intval(I("post.catID")):"";
    	//!empty($_POST['isSelf'])?$where['hui_goods.commentType']=1:$where['hui_goods.commentType']=0;
		isset($_POST['isSelf'])?$where['hui_goods.commentType']=intval(I("post.isSelf")):"";
    	
    	empty($_POST['page'])?$page=1:$page=intval(I("post.page"));
    	empty($_POST['pageSize'])?$pageSize=15:$pageSize=intval(I("post.pageSize"));
		
		isset($_POST['shop'])?$shop=intval(I("post.shop")):$shop=0;
		
		/*!empty($_GET['shopID'])?$where['shopID']=intval(I("shopID")):"";
    	!empty($_GET['catID'])?$where['catID']=intval(I("catID")):"";
    	//!empty($_POST['isSelf'])?$where['hui_goods.commentType']=1:$where['hui_goods.commentType']=0;
		isset($_GET['isSelf'])?$where['hui_goods.commentType']=intval(I("isSelf")):"";
		empty($_POST['page'])?$page=1:$page=intval(I("post.page"));
    	empty($_POST['pageSize'])?$pageSize=15:$pageSize=intval(I("post.pageSize"));
		isset($_GET['shop'])?$shop=intval(I("shop")):$shop=0;
		
		//$where['hui_goods.commentType']=intval(I("isSelf"));
		//var_dump($where);exit;*/
		
    	$order="ind asc,goodsID desc";
    	
    	$where['hui_goods.isOn']=1;
    	$where['isSale']=1;
    	
    	$count=D("Goods")->getGoodsListLength($where);//var_dump(D("Goods")->getLastSql());exit;
		
    	if ($count=="0") $this->_returnJson(array("result"=>0,"info"=>"no data","code"=>"139"));
    	
    	$pageCount=ceil($count/$pageSize);
    	if ($pageCount < $page) $this->_returnJson(array("result"=>0,"info"=>"page too big","code"=>"114"));
    	
    	$field="goodsID,shopID,goodsName,goodsSn,num,restNum,limitNum,hui_goods.catID,goodsPrice,marketPrice,unit,headImg,thumb,hui_goods.commentType";
    	$field.=",isTimeLimit,limitStartTime,limitEndTime,saleNum";
		if($shop!=0){
    	$goodsList = D("Goods")->getGoodsList1($shop, $page, $pageSize, $where, $order,$field);
		} else{
			$goodsList = D("Goods")->getGoodsList($page, $pageSize, $where, $order,$field);
		}
    	//file_put_contents("goods.txt", D("Goods")->getLastSql());
    	
    	if ($goodsList && !empty($this->user['uid'])){
    		
    		foreach ($goodsList as $key=>$a){
    			$hasBuyNum=D('OrderGoods')->field('ifnull(sum(num),0) as num')->where(array('userID'=>$this->user['uid'],'goodsID'=>$a['goodsID'],'status'=>1,'isOn'=>1))->find();
    			$goodsList[$key]['hasBuyNum']=$hasBuyNum['num'];
    		}
    	}
    	
    	
    	$this->_returnJson(array("result"=>1,"list"=>$goodsList,"page"=>array("page"=>$page,"pageSize"=>$pageSize,"pageCount"=>$pageCount),"host"=>C('IMG_DOMAIN')));
    }
    
    //获取单个商品
    public function goods(){
    	!empty($_POST['goodsID'])?$goodsID=intval(I("post.goodsID")):$this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
    	!empty($_POST['getShop'])?$getShop=I("post.getShop"):"";
    	$where['isOn']=1;
    	
    	$field="goodsID,shopID,goodsName,goodsSn,num,restNum,limitNum,catID,unit,goodsPrice,marketPrice,headImg,thumb,desc,isSale,commentType";
    	$field.="isTimeLimit,limitStartTime,limitEndTime,saleNum";
    	$goods=D("Goods")->getGoods($goodsID);
    	
    	if (!$goods) $this->_returnJson(array("result"=>0,"info"=>"goods not exist","code"=>"116"));
    	if (!$goods['isSale']) $this->_returnJson(array("result"=>0,"info"=>"goods not sale","code"=>"117"));
    	    	
    	if(!empty($getShop)){
    	    $field="shopID,shopName,province,city,district,address,desc,x,y,headImg,thumb,shopGrade,goodsGrade,orderNum,saleNum";
    	    $field.="goodsCommentNum,shopCommentNum,shopType,allowCard,isWork";
    	    $shop=D("Shop")->getShop("",$goods['shopID'],array("isOn"=>1),"shopName,desc");
    	    $goods['shopInfo']=$shop;
    	}
    	
    	$goods['host']=C('IMG_DOMAIN');
    	//$goodsCat=D('GoodsCat')->field('catName,code')->where(array('catID'=>$goods['catID']))->find();
    	//$goods['goodsType']=empty($goodsCat['code'])?0:1;
		$goods['goodsType']=$goods['commentType'];
		$goodsCat=D('GoodsCat')->field('code')->where(array('catID'=>$goods['catID']))->find();
    	$goods['code']=empty($goodsCat['code'])?0:1;
    	
    	if (!empty($this->user['uid'])){
    		$hasBuyNum=D('OrderGoods')->field('ifnull(sum(num),0) as num')->where(array('userID'=>$this->user['uid'],'goodsID'=>$goodsID,'status'=>1,'isOn'=>1))->find();
    		$goods['hasBuyNum']=$hasBuyNum['num'];
    		
    	}
    	
    	$this->_returnJson(array("result"=>1,"goods"=>$goods,"url"=>getHost().U("Home/Index/goodsDetail",array("goodsID"=>$goodsID))));
    }
    
    
    private function _dealShopList(&$shopList,$commentType=1) {
        if(empty($shopList)) return false;
        
        foreach ($shopList as $key=>$a){
            $shopStr[]=$a['shopID'];
    	}
    	$shopStrID=implode(",", $shopStr);
    	$count=D("Goods")->field("count(*) as num,shopID")->where(array("shopID"=>array("IN",$shopStrID),"isOn"=>1,"isSale"=>1,"commentType"=>$commentType))->group("shopID")->select();
    	
    	foreach ($shopList as $key=>$a){
    	    foreach ($count as $key2=>$b){
    	        if($b['shopID']==$a['shopID']){
    	            if (count($b['num']>0)){
    	                $shopList[$key]['isTicket']="1";
    	                unset($count[$key2]);
    	                continue 2;
    	            }
                }
    	    }
    	    
    	    $shopList[$key]['isTicket']="0";
    	    unset($count[$key2]);
    	}
    }
    
    //经纬度之间距离计算
    private function _rad($d)
    {
    	return $d * 3.1415926535898 / 180.0;
    }
    
    private function _getDistance($lat1, $lng1, $lat2, $lng2)
    {
    	$EARTH_RADIUS = 6378.137;
    	$radLat1 = $this->_rad($lat1);
    	//echo $radLat1;
    	$radLat2 = $this->_rad($lat2);
    	$a = $radLat1 - $radLat2;
    	$b = $this->_rad($lng1) - $this->_rad($lng2);
    	$s = 2 * asin(sqrt(pow(sin($a/2),2) +
    			cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)));
    	$s = $s *$EARTH_RADIUS;
    	$s = round($s * 10000) / 10000;
    	return $s;
    }
    
    
    
    
}